package com.chj.comp.common.core.util;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.core.constant.CommonConstant;
import com.chj.comp.common.core.dto.SysUserDTO;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 安全工具类
 *
 * @author cuihui
 */
@Slf4j
@UtilityClass
public class SecurityUtil {

    /**
     * 获取Authentication
     */
    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取OAuth2Request
     * @return
     */
    private OAuth2Request getOAuth2Request() {
        Authentication authentication = getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request();
        }
        return null;
    }

    /**
     * 获取用户
     *
     * @param
     * @return SysUserDTO
     * <p>
     */
    public SysUserDTO getUser() {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            String principal = authentication.getPrincipal().toString();
            if (principal != null) {
                try {
                    SysUserDTO sysUserDTO = JSON.parseObject(principal, SysUserDTO.class);
                    return sysUserDTO;
                } catch (Exception e) {
                    log.error("获取用户失败，principal-->" + principal);
                }
            }
        }
        return null;
    }

    /**
     * 获取当前登录的用户id
     */
    public Integer getUserId() {
        SysUserDTO user = getUser();
        if (user == null){
            return null;
        }
        return user.getId();
    }

    /**
     * 获取当前登录的用户名
     */
    public static String getUserName() {
        SysUserDTO user = getUser();
        if (user == null){
            return null;
        }
        return user.getUsername();
    }

    /**
     * 获取当前登录的用户全名
     */
    public static String getFullName() {
        SysUserDTO user = getUser();
        if (user == null){
            return null;
        }
        return user.getFullname();
    }

    /**
     * 获取用户角色集合
     *
     * @return 角色集合
     */
    public List<String> getRoles() {
        Authentication authentication = getAuthentication();
        if(authentication != null){
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            List<String> roleCodes = new ArrayList<>();
            authorities.stream().forEach(permission -> {
                String s = permission.getAuthority();
                if(s.startsWith(CommonConstant.ROLE)){
                    roleCodes.add(s.substring(CommonConstant.ROLE.length()));
                }
            });
            return roleCodes;
        }
        return null;
    }

    /**
     * 获取用户权限集合
     *
     * @return 权限集合
     */
    public List<String> getPermissions() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<String> roleCodes = new ArrayList<>();
        authorities.stream().forEach(permission -> {
            String s = permission.getAuthority();
            if(!s.startsWith(CommonConstant.ROLE)){
                roleCodes.add(s);
            }
        });
        return roleCodes;
    }

    /**
     * 获取当前客户端ID
     *
     * @return
     */
    public String getClientId() {
        OAuth2Request oAuth2Request = getOAuth2Request();
        if(oAuth2Request != null){
            return oAuth2Request.getClientId();
        }
        return null;
    }

    /**
     *
     * @return
     */
    public List<String> getScope(){
        OAuth2Request oAuth2Request = getOAuth2Request();
        if(oAuth2Request != null){
            Set<String> scope = oAuth2Request.getScope();
            if (CollectionUtils.isNotEmpty(scope)) {
                return new ArrayList<>(scope);
            }
        }
        return null;
    }
}
